﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper.Internal.Mappers;
using DocumentFormat.OpenXml.Spreadsheet;
using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using ERP.Common.Results;

namespace ERP.ERPSystem.ProductionSystem
{
    /// <summary>
    /// 生产系统-生产退料
    /// </summary>
    public class ProductionMaterialReturnServices:ApplicationService,IProductionMaterialReturnServices
    {
        private readonly IRepository<ProductionMaterialReturn> _materreturnrepository;

        public ProductionMaterialReturnServices(IRepository<ProductionMaterialReturn> materreturnrepository)
        {
            this._materreturnrepository = materreturnrepository;
        }

        /// <summary>
        /// 添加生产退料
        /// </summary>
        /// <param name="productionMaterialReturnDto"></param>
        /// <returns></returns>
        public async Task<int> AddPMateriaReturn(ProductionMaterialReturnDto productionMaterialReturnDto)
        {
            var addmater = ObjectMapper.Map<ProductionMaterialReturnDto, ProductionMaterialReturn>(productionMaterialReturnDto);
            var i=await _materreturnrepository.InsertAsync(addmater);
            return  i==null? 0 : 1;
        }

        /// <summary>
        /// 显示生产退料
        /// </summary>
        /// <returns></returns>
        public async Task<List<ProductionMaterialReturn>> GetPMateriaReturn()
        {
            var materrerurnlistr=await _materreturnrepository.GetListAsync();
            return materrerurnlistr;
        }

        /// <summary>
        /// 获取生产退料列表（分页和搜索）
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <param name="returnOrderCode">退料单编号</param>
        /// <param name="returnOrderName">退料单名称</param>
        /// <param name="productionWorkOrder">生产工单</param>
        /// <param name="warehouse">仓库</param>
        /// <returns></returns>
        public async Task<APIPaging<ProductionMaterialReturn>> GetProductionMaterialReturnList(
            int page = 1, 
            int limit = 10, 
            string returnOrderCode = "", 
            string returnOrderName = "", 
            string productionWorkOrder = "", 
            string warehouse = "")
        {
            try
            {
                APIPaging<ProductionMaterialReturn> pageList = new APIPaging<ProductionMaterialReturn>();
                
                // 获取生产退料数据
                var materialReturnQueryable = await _materreturnrepository.GetQueryableAsync();
                
                // 应用搜索条件
                materialReturnQueryable = materialReturnQueryable.WhereIf(!string.IsNullOrEmpty(returnOrderCode), m => m.ReturnOrderCode.Contains(returnOrderCode));
                materialReturnQueryable = materialReturnQueryable.WhereIf(!string.IsNullOrEmpty(returnOrderName), m => m.ReturnOrderName.Contains(returnOrderName));
                materialReturnQueryable = materialReturnQueryable.WhereIf(!string.IsNullOrEmpty(productionWorkOrder), m => m.ProductionWorkOrder.Contains(productionWorkOrder));
                materialReturnQueryable = materialReturnQueryable.WhereIf(!string.IsNullOrEmpty(warehouse), m => m.ReceiveWarehouse.Contains(warehouse));
                
                var materialReturnList = materialReturnQueryable.ToList();
                
                // 分页处理
                pageList.PageCount = materialReturnList.Count();
                pageList.ListDate = materialReturnList.OrderByDescending(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
                pageList.PageIndex = Convert.ToInt32(Math.Ceiling(pageList.PageCount * 1.0 / limit));
                
                return pageList;
            }
            catch (Exception)
            {
                throw;
            }
        }
        
        /// <summary>
        /// 更新生产退料
        /// </summary>
        /// <param name="entity">更新数据</param>
        /// <returns></returns>
        [Volo.Abp.Uow.UnitOfWork]
        public async Task<int> UpdatePMateriaReturn(ProductionMaterialReturn entity)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"服务层开始更新: ID={entity.Id}");
                
                // 直接更新实体，因为控制器已经获取并修改了实体
                await _materreturnrepository.UpdateAsync(entity, autoSave: true);
                
                System.Diagnostics.Debug.WriteLine($"服务层更新完成: ID={entity.Id}");
                return 1;
            }
            catch (Volo.Abp.Domain.Entities.EntityNotFoundException)
            {
                System.Diagnostics.Debug.WriteLine($"服务层记录不存在: ID={entity.Id}");
                return 0;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"服务层更新异常: {ex.Message}, StackTrace: {ex.StackTrace}");
                throw;
            }
        }
        
        /// <summary>
        /// 删除生产退料
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns></returns>
        public async Task<int> DeletePMateriaReturn(int id)
        {
            try
            {
                // 查找要删除的记录
                var existingItem = await _materreturnrepository.FindAsync(x => x.Id == id);
                if (existingItem == null)
                {
                    return 0; // 记录不存在
                }
                
                // 删除记录
                await _materreturnrepository.DeleteAsync(existingItem);
                return 1;
            }
            catch (Exception)
            {
                throw;
            }
        }
        
        /// <summary>
        /// 批量删除生产退料
        /// </summary>
        /// <param name="ids">记录ID数组</param>
        /// <returns></returns>
        public async Task<int> BatchDeletePMateriaReturn(int[] ids)
        {
            try
            {
                int deletedCount = 0;
                
                foreach (var id in ids)
                {
                    var existingItem = await _materreturnrepository.FindAsync(x => x.Id == id);
                    if (existingItem != null)
                    {
                        await _materreturnrepository.DeleteAsync(existingItem);
                        deletedCount++;
                    }
                }
                
                return deletedCount;
            }
            catch (Exception)
            {
                throw;
            }
        }
        
        /// <summary>
        /// 根据ID获取单个生产退料记录
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns></returns>
        public async Task<ProductionMaterialReturn> GetPMateriaReturnById(int id)
        {
            try
            {
                var item = await _materreturnrepository.FindAsync(x => x.Id == id);
                return item;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
